<template>
  <div class="form-page news-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px"
        ></span>
        推送信息
      </p>
      <p slot="extra" style="color: #999; font-size: 12px">
        <label style="color: #ff3b30">*</label> 为必填
      </p>
      <Form
        ref="formModel"
        :rules="ruleValidate"
        :model="bloc.form"
        :label-width="150"
        label-position="right"
      >
        <div class="title-tips">编辑消息内容</div>
        <FormItem label="消息标题:" prop="title" required>
          <Input
            type="text"
            v-model="bloc.form.title"
            placeholder="请填写消息标题"
            style="width: 400px; height: 40px"
            :disabled="bloc.isDetail"
          />
        </FormItem>
        <FormItem label="消息类型:" prop="newsType" required>
          <RadioGroup v-model="bloc.form.newsType">
            <Radio label="PUSH_INFORM" :disabled="bloc.isDetail && bloc.form.newsType === 'IN_STATION_INFORM'">消息通知</Radio>
            <Radio label="IN_STATION_INFORM" :disabled="bloc.isDetail && bloc.form.newsType === 'PUSH_INFORM'">应用内消息</Radio>
          </RadioGroup>
          <span style="margin-left: 20px; color: #c2c7d0">{{
            showTypeTips
          }}</span>
        </FormItem>
        <FormItem label="通知类型:" prop="type" required>
          <RadioGroup v-model="bloc.form.type">
            <Radio :label="0" >服务通知</Radio>
            <!-- <Radio :label="1" >活动</Radio> -->
          </RadioGroup>
        </FormItem>
        <!--        <FormItem label="消息缩列图:">-->
        <!--          <div class="demo-upload-list mar-left" v-for="(item, index) in fileList" :key="index">-->
        <!--            <template v-if="item.status === 'finished'">-->
        <!--              <img :src="item.url">-->
        <!--              <div class="demo-upload-list-cover">-->
        <!--                <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>-->
        <!--                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>-->
        <!--              </div>-->
        <!--            </template>-->
        <!--            <template v-else>-->
        <!--              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>-->
        <!--            </template>-->
        <!--          </div>-->
        <!--          <Upload-->
        <!--            v-show="fileList.length < 1"-->
        <!--            :class="{'mar-left': fileList.length <= 0}"-->
        <!--            ref="upload"-->
        <!--            :show-upload-list="false"-->
        <!--            :format="['jpg','jpeg','png']"-->
        <!--            :max-size="2048"-->
        <!--            :headers="uploadHeaders"-->
        <!--            :action="uploadAction"-->
        <!--            :on-success="handleSuccess"-->
        <!--            :on-format-error="handleFormatError"-->
        <!--            :on-exceeded-size="handleMaxSize"-->
        <!--            multiple-->
        <!--            type="drag"-->
        <!--            style="display: inline-block;width:58px;">-->
        <!--            <div style="width: 58px;height:58px;line-height: 58px;">-->
        <!--              <Icon type="ios-camera" size="20"></Icon>-->
        <!--            </div>-->
        <!--          </Upload>-->
        <!--          <Modal title="View Image" v-model="visible">-->
        <!--            <img :src="imgUrl" v-if="visible" style="width: 100%">-->
        <!--          </Modal>-->
        <!--        </FormItem>-->
        <FormItem label="消息内容:" prop="body" required>
          <Input
            type="textarea"
            :rows="4"
            v-model="bloc.form.body"
            maxlength="300"
            show-word-limit
            placeholder="最大300字..."
            style="width: 400px"
            :disabled="bloc.isDetail"
          />
        </FormItem>
        <div class="title-tips">选择目标人群</div>
        <FormItem label="目标人群:" prop="targetGroup" required>
          <RadioGroup v-model="bloc.form.targetGroup">
            <Radio label="ALL_MEMBER" :disabled="isHasMemberInfo"
              >全体会员</Radio
            >
            <Radio label="PART_MEMBER" :disabled="!isHasMemberInfo">部分会员</Radio>
          </RadioGroup>
          <span v-if="isHasMemberInfo" style="margin-left: 20px; color: #c2c7d0"
            >已选择会员
<!--            <Button-->
<!--              type="primary"-->
<!--              style="margin-left: 60px; width: 100px"-->
<!--              @click="handledetail()"-->
<!--              :loading="btnload.loading"-->
<!--              v-if="isHasMemberInfo"-->
<!--            >查看-->
<!--          </Button>-->
          </span>

          <!--          <Input-->
          <!--            v-else-->
          <!--            class="member-input"-->
          <!--            type="textarea"-->
          <!--            :rows="4"-->
          <!--            :autosize="{maxRows: 4,minRows: 4}"-->
          <!--            v-model="bloc.form.targetAccountsTxt"-->
          <!--            maxlength="300"-->
          <!--            :placeholder="plTargetMember"-->
          <!--            style="width: 400px;margin-top: 10px;"/>-->
        </FormItem>
        <div class="title-tips">发送策略</div>
        <!--        <FormItem label="推送时间:" prop="pushType" required>-->
        <!--          <div>-->
        <!--            <Select style="width: 220px" v-model="bloc.form.pushType" placeholder="推送方式">-->
        <!--              <Option value="TIMING">定时推送</Option>-->
        <!--              <Option value="REAL_TIME">实时推送</Option>-->
        <!--            </Select>-->
        <!--            <DatePicker-->
        <!--              v-if="bloc.form.pushType === 'TIMING'"-->
        <!--              type="datetime"-->
        <!--              placeholder="选择时间"-->
        <!--              v-model="bloc.form.pushTime"-->
        <!--              style="width: 200px;margin-left: 10px"></DatePicker>-->
        <!--          </div>-->
        <!--        </FormItem>-->
        <FormItem label="后续动作:" prop="actionData" required>
          <RadioGroup v-model="bloc.form.actions">
            <Radio label="OPEN_URL" :disabled="bloc.isDetail && bloc.form.actions === 'OPEN_NEWS'">打开链接</Radio>
<!--            <Radio label="OPEN_INFO">打开资讯</Radio>-->
            <Radio label="OPEN_NEWS" :disabled="bloc.isDetail && bloc.form.actions === 'OPEN_URL'">打开消息</Radio>
          </RadioGroup>

          <Input
            type="text"
            v-show="bloc.form.actions !== 'OPEN_NEWS'"
            v-model="bloc.form.actionData"
            :placeholder="plToplay"
            style="width: 400px; margin-top: 10px"
            :disabled="bloc.isDetail"
          />
        </FormItem>
      </Form>
      <div style="margin: 20px 0px 35px 25px">
        <router-link :to="{ path: '/news/list' }">
          <Button style="width: 100px; height: 40px" @click="handleCancel()">返回</Button>
        </router-link>
        <Button
          type="primary"
          style="margin-left: 30px; width: 100px; height: 40px"
          @click="handleOk('formModel')"
          :loading="btnload.loading"
          :disabled="bloc.isDetail"
          >保存
        </Button>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { Route } from 'vue-router';
import { FormBloc } from '@/view/news/FormBloc';
import { baseUrl } from '@/base/Request';
import { store } from '@/store/Store';
import { Loading } from '@/base/Loading';
import { isEmpty } from '@/base/util/Strings';
import { getValidateHttp, getValidateMaxString } from '@/base/util/Validate';
import time from 'view-design/src/components/time/time';

@Component
export default class extends Vue {
  beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
    next((vm) => {
      vm.bloc.isDetail = vm.$route.query.detail === '1';
      if (!vm.isAdd) vm.bloc.load(vm.idx);
    });
  }

  get isAdd() {
    return !this.idx;
  }

  get idx() {
    return Number(this.$route.params.id);
  }

  get isHasMemberInfo() {
    const sessinStr = sessionStorage.getItem('MEMBER_INFO');
    const info = sessinStr ? JSON.parse(sessinStr) : undefined;
    if (info) {
      this.bloc.form.targetAccounts = info.map((x) => x.id);
      this.bloc.form.targetGroup = 'PART_MEMBER';
    }
    return this.bloc.form.targetAccounts.length >= 1;
  }

  get uploadAction() {
    return `${baseUrl}/api/upload/image`;
  }

  get uploadHeaders() {
    return {
      Authorization: 'Bearer ' + store.state.auth.accessToken
    };
  }

  get fileList() {
    return this.bloc.form.images.map((x) => {
      return { name: 'name', url: x, status: 'finished' };
    });
  }

  get showTypeTips() {
    return this.bloc.form.newsType === 'PUSH_INFORM'
      ? '将消息推送给用户'
      : '不推送消息，仅在用户APP消息栏目展示';
  }

  get plToplay() {
    return this.bloc.form.actions === 'OPEN_URL'
      ? '请填写以http或https开头的地址'
      : '请填写ID号';
  }

  get getActionTips() {
    const obj = {
      OPEN_URL: '打开链接',
      // OPEN_INFO: "打开资讯",
      OPEN_NEWS: '打开消息'
    };
    return obj[this.bloc.form.actions];
  }

  bloc: FormBloc = new FormBloc();
  btnload = new Loading();
  plTargetMember =
    '输入用户电话号码，多个用户请回车换行，一行一个;\n如果所输入的电话号码不属于当前品牌商会员，则不对此号码推送消息;';
  imgUrl = '';
  visible = false;
  ruleValidate = {
    title: [
      {
        validator: (rule, value, callback) => {
          if (isEmpty(value)) callback(new Error('消息标题不能为空'));
          else if (getValidateMaxString(15, value)) { callback(new Error('消息标题的长度不能超过15')); } else callback();
        },
        trigger: 'blur'
      }
    ],
    actionData: [
      {
        validator: (rule, value, callback) => {
          if (isEmpty(value)) {
            if (this.bloc.form.actions !== 'OPEN_NEWS') {
              callback(new Error(`${this.getActionTips}不能为空`));
            } else {
              callback();
            }
          } else if (
            this.bloc.form.actions === 'OPEN_URL' &&
            !getValidateHttp(this.bloc.form.actionData)
          ) { callback(new Error('打开链接格式不正确')); } else callback();
        },
        trigger: 'blur'
      }
    ],
    body: [{ required: true, message: '请填写推送内容', trigger: 'blur' }]
  };

  handleView(url) {
    this.imgUrl = url;
    this.visible = true;
  }

  handleRemove(file) {
    this.bloc.form.images.splice(this.bloc.form.images.indexOf(file), 1);
  }

  handleSuccess(res, file) {
    this.bloc.form.images.push(res.data[0]);
  }

  handleFormatError(file) {
    this.$Notice.warning({
      title: 'The file format is incorrect',
      desc:
        'File format of ' +
        file.name +
        ' is incorrect, please select jpg or png.'
    });
  }

  handleMaxSize(file) {
    this.$Notice.warning({
      title: 'Exceeding file size limit',
      desc: 'File is too large, no more than 2M.'
    });
  }

  handleCancel() {
    this.$router.push({ path: `/news/list` });
    sessionStorage.removeItem('MEMBER_INFO');
    // sessionStorage.getItem('MEMBER_INFO')
  }
  handledetail() {
    this.$router.push({ path: `/news/list` });
  }
  handleOk(name) {
    // if (this.bloc.form.pushType === 'TIMING' && isEmpty(this.bloc.form.pushTime)) {
    //   this.$Message.error('推送时间不能为空');
    //   return;
    // }
    const formRef: any = this.$refs[name];
    formRef.validate((valid) => {
      if (valid) {
        this.saveFn();
      }
    });
  }

  saveFn() {
    this.btnload.loading = true;
    this.bloc.form.pushType = 'REAL_TIME';
    this.bloc.form.pushTime = new Date() + '';
    // if (this.bloc.form.pushType === 'REAL_TIME') this.bloc.form.pushTime = new Date() + '';
    const parmas = this.isAdd ? '' : this.idx;
    this.bloc
      .save(parmas)
      .then((res) => {
        this.$Message.success('保存推送成功');
        this.btnload.loading = false;
        this.handleCancel();
      })
      .catch((err) => {
        this.btnload.loading = false;
        this.$Message.error({ content: err.message, duration: 6000 });
        this.handleCancel();
        console.log('出错啦::::', err);
      });
  }
}
</script>

<style lang="less" scoped>
.mar-left {
  margin-left: 15px;
}
.title-tips {
  font-weight: bolder;
  margin-bottom: 20px;
  text-align: left;
  &:before {
    content: "|";
    width: 4px;
    height: 10px;
    color: #2d8cf0;
    background: #2d8cf0;
    margin-right: 10px;
  }
}
</style>
